package com.kfm.goods.controller;

import com.github.pagehelper.PageInfo;
import com.kfm.goods.domain.User;
import com.kfm.goods.ex.ServiceException;
import com.kfm.goods.service.UserService;
import com.kfm.goods.util.Resp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public String user(){
        System.out.println("handler loginPage()...");
        return "user";
    }


    @GetMapping("/index")
    public ModelAndView indexPage(){
        return new ModelAndView("user/index");
    }

    @GetMapping("/list")
    public PageInfo list(@RequestParam(value = "page", defaultValue = "1")int page
            , @RequestParam(value = "limit", defaultValue = "5") int pageSize
    , User user) throws ServiceException {
        return new PageInfo<>(userService.findAll(page, pageSize, user));
    }

    @GetMapping("/edit")
    public ModelAndView editPage(@RequestParam(required = false) String id){
        ModelAndView modelAndView = new ModelAndView("user/edit");
        if (id != null) {
            // 修改
            modelAndView.addObject("user", userService.findById(id));
        } else {
            modelAndView.addObject("user", new User());
        }
        return modelAndView;
    }

    @PostMapping("/edit")
    public Resp edit(User user){
        try {
            userService.update(user);
            return Resp.ok();
        } catch (ServiceException e) {
            e.printStackTrace();
            return Resp.error("更新失败，请重试");
        }
    }



}
